package com.sumer.psychology.common.port.adapter.service;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.common.BusinessException;
import com.sumer.psychology.common.domain.model.User;
import com.sumer.psychology.common.domain.model.UserTranslator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * 访问http接口获得User信息
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/11/20
 * Time: 8:49
 */
public class HttpUserInRoleAdapter implements UserInRoleAdapter {
    private static Logger logger = LoggerFactory.getLogger(HttpUserInRoleAdapter.class);

    private String userInfoUrlTemplate;
    private String userIdUrlTemplate;
    private String userEditTemplate;
    private String passwordChangeTemplate;

    public HttpUserInRoleAdapter(String urlTemplate, String userIdUrlTemplate, String userEditTemplate, String passwordChangeTemplate) {
        this.userInfoUrlTemplate = urlTemplate;
        this.userIdUrlTemplate = userIdUrlTemplate;
        this.userEditTemplate = userEditTemplate;
        this.passwordChangeTemplate = passwordChangeTemplate;
    }

    @Override
    public User toUser(String anIdentity) {
        Assert.notEmpty(anIdentity, "人员ID不能为空");

        User user;

        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(userInfoUrlTemplate())
                    .resolveTemplate("id", anIdentity)
                    .request(MediaType.APPLICATION_JSON_TYPE)
                    .get();

            if (response.getStatus() == 200) {
                user = new UserTranslator().toUserFromRepresentation(
                        response.readEntity(String.class));
            } else if (response.getStatus() == 204) {
                user = null;
            } else {
                throw new IllegalStateException(
                        "访问User出现失败信息："
                                + anIdentity
                                + "状态码是："
                                + response.getStatus());
            }
        } catch (Exception e) {
            throw new BusinessException(
                    "获得User信息失败，原因是:" + e.getMessage(), e);
        }

        return user;
    }

    @Override
    public String userId(String uId, String uIdPk) {
        if (StringUtils.isAnyBlank(uId, uIdPk)) {
            return null;
        }

        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(userIdUrlTemplate())
                    .resolveTemplate("uid", uId)
                    .resolveTemplate("uidpk", uIdPk)
                    .request()
                    .get();

            if (response.getStatus() == 200) {
                return response.readEntity(String.class);
            } else if (response.getStatus() == 204) {
                return null;
            } else {
                throw new IllegalStateException(
                        "获取当前用户ID出现失败信息："
                                + uId + "/" + uIdPk
                                + " 状态码是："
                                + response.getStatus());
            }
        } catch (Exception e) {
            throw new BusinessException(
                    "获得UserID信息失败，原因是:" + e.getMessage(), e);
        }
    }

    @Override
    public void editUser(String userId, String parameters) {
        if (StringUtils.isAnyBlank(userId)) {
            return;
        }

        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(userEditTemplate() + parameters)
                    .resolveTemplate("userid", userId)
                    .request()
                    .get();

            logger.info("提交User，结果状态码是{}", response.getStatus());

        } catch (Exception e) {
            throw new BusinessException(
                    "提交User信息失败，原因是：" + e.getMessage(), e);
        }
    }

    @Override
    public void changePassword(String userId, String parameters) {
        if (StringUtils.isAnyBlank(userId)) {
            return;
        }

        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(passwordChangeTemplate() + parameters)
                    .resolveTemplate("userid", userId)
                    .request()
                    .get();

            logger.info("修改密码，结果状态码是{}", response.getStatus());

        } catch (Exception e) {
            throw new BusinessException(
                    "修改密码错误，原因是：" + e.getMessage(), e);
        }
    }

    private String userInfoUrlTemplate() {
        return userInfoUrlTemplate;
    }

    private String userIdUrlTemplate() {
        return userIdUrlTemplate;
    }

    private String userEditTemplate() {
        return userEditTemplate;
    }

    private String passwordChangeTemplate() {
        return passwordChangeTemplate;
    }
}
